package com.mygdx.game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;

/**
 * 游戏杆
 * Created by 80002023 on 2016/8/5.
 */
public class TouchpadDemo extends Game {

    SpriteBatch batch;
    Stage stage;
    Touchpad touchpad;
    Texture player;

    int speed = 3;
    int x, y;

    @Override
    public void create() {
        batch = new SpriteBatch();
        stage = new Stage();
        Gdx.input.setInputProcessor(stage);

        player = new Texture(Gdx.files.internal("data/2.png"));

        Texture texture = new Texture(Gdx.files.internal("data/btn/touchpad.png"));

        TextureRegionDrawable background = new TextureRegionDrawable(new TextureRegion(texture, 0, 0, 128, 128));
        TextureRegionDrawable knob = new TextureRegionDrawable(new TextureRegion(texture, 128, 0, 128, 128));

        Touchpad.TouchpadStyle touchpadStyle = new Touchpad.TouchpadStyle(background, knob);

        touchpad = new Touchpad(15, touchpadStyle);

        touchpad.setBounds(0, 0, 150, 150);

        stage.addActor(touchpad);
    }

    public void update() {
        if (touchpad.isTouched()) {
            x += touchpad.getKnobPercentX() * speed;
            y += touchpad.getKnobPercentY() * speed;
        }
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        update();

        batch.begin();
        batch.draw(player, x, y, 50, 50);
        batch.end();

        stage.act();
        stage.draw();
    }
}
